var express = require('express');
var router = express.Router();
let { mzhModel } = require('../model/mzh')
const jwt = require('jsonwebtoken');
const JWT_SECRET = 'zihang'; //JWT签名
router.post("/logins", async (req, res) => {
    let username = req.body.username
    let password = req.body.password
    let data = await mzhModel.find({ username: username })
    const token = jwt.sign({ username: username }, JWT_SECRET, { expiresIn: '1h' }); //生成token,并且转为字符转
    if (data.length) {
        if (data[0].password == password) {
            res.send({ code: 200, msg: '登录成功', token })
        } else {
            res.send({ code: 201, msg: '密码错误' })
        }
    } else {
        res.send({ code: 202, msg: '账号不存在' })
    }
})
router.get('/indexs', (res, req) => {
    //jwt expired token失效
    if (res.headers.authorization == 'Bearer') {
        console.log('没有token');
        return req.send({ code: 201, msg: '没有token' });
    } else {
        let token = JSON.parse(res.headers.authorization.slice(7));
        jwt.verify(token, JWT_SECRET, (err, decode) => {
            if (err == null) {
                console.log('token有效');
                return req.send({ code: 200, msg: 'token验证成功' });
            } else if (err) {
                console.log('token失效');
                return req.send({ code: 201, msg: 'token失效' });
            }
        },
        )
    }
})

module.exports = router;